<template>
    <el-card class="page-card">
        <!-- form 查询表单 -->
        <el-form :model="dishes" ref="formRef" label-width="auto" label-position="right" style="padding-bottom: 10px;">
            <el-row :gutter="20">
                <el-col :span="5">
                    <el-form-item label="菜名" prop="name">
                        <el-input v-model="dishes.name" placeholder="请输入菜名" clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="价格" prop="price">
                        <el-input v-model="dishes.price" placeholder="请输入价格" clearable/>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="状态" prop="state">
                        <el-select v-model="dishes.state" placeholder="状态" clearable>
                            <el-option label="全部" value="" />
                            <el-option label="上架" value="1" />
                            <el-option label="下架" value="0" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="分类" prop="dishes_class">
                        <el-select v-model="dishes.dishes_class" placeholder="类型" clearable>
                            <el-option label="全部" value="" />
                            <el-option label="主食" value="主食" />
                            <el-option label="菜品" value="菜品" />
                            <el-option label="加菜" value="加菜" />
                            <el-option label="饮料" value="饮料" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-button type="primary" @click="doList">查询</el-button>
                    <el-button type="default" @click="resetForm(formRef)">重置</el-button>
                    <el-button type="success" @click="showAddDialog">新增</el-button>
                </el-col>
            </el-row>
        </el-form>

        <!-- 菜品卡片展示区域 -->
        <div class="dish-grid">
            <div 
                v-for="(item, index) in tableData" 
                :key="index" 
                class="dish-card"
                @mouseover="showActions(index)" 
                @mouseleave="hideActions(index)"
                @click="showDetailPage(item)"
            >
                <img :src="'/api' + item.picture" alt="菜品图片" class="dish-image" />
                <div class="dish-name">{{ item.name }}</div>
                <div class="dish-price">￥{{ item.price}}</div>
                <div  class="dish-actions">
                    <el-button type="text" @click.stop="showUpdateDialog(item)">更新</el-button>
                    <el-button type="text" @click.stop="doDelete(item.id)">删除</el-button>
                </div>
            </div>
        </div>
    </el-card>

    <!-- 分页控件 -->
    <div class="pagination">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>

    <!-- 新增 dialog-->
    <el-dialog v-model="addDialogVisible" title="新增菜品" width="40%" top="2vh" destroy-on-close>
        <add-page
            @flushPage="doFlushPage"
            @closeDialog="addDialogVisible = false">
        </add-page>
    </el-dialog>

    <!-- 更新 dialog-->
    <el-dialog v-model="updateDialogVisible" title="更新菜品" width="40%" top="2vh" destroy-on-close>
        <update-page ref="updatePageRef"
             @flushPage="doFlushPage"
             @closeDialog="updateDialogVisible = false">
        </update-page>
    </el-dialog>

    <!-- 详情 页面 -->
    <detail-page ref="detailPageRef"></detail-page>
</template>

<script setup lang="ts">
import {ref, onMounted, nextTick} from 'vue'
import {ElMessage, FormInstance} from "element-plus";
import axios from 'axios'
import DetailPage from './DetailPage.vue';
import AddPage from './AddPage.vue';
import UpdatePage from './UpdatePage.vue';
import {useRoute} from "vue-router";

// 获取当前店铺ID
const shopId = localStorage.getItem('shopInfo') ? JSON.parse(localStorage.getItem('shopInfo')).id : null;

if (!shopId) {
    ElMessage.error('未找到店铺信息，请先登录');
}

const formRef = ref<FormInstance>();
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// form 查询表单绑定的数据对象：dishes
const dishes = ref({
    id: '',
    name: '',
    price: '',
    shop_id: shopId,
    state: '',
    picture: '',
    dishes_class: ''
});

// table 数据表格绑定的数据对象：tableData
const tableData = ref([]);
// 每个菜品的操作按钮是否可见
const actionsVisible = ref([]);

// 查询
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);

// 处理分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val;
    doList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
    currentPage.value = val;
    doList();
};

const doList = async () => {
    const params = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        ...dishes.value
    };

    const {data} = await axios.get('/api/dishesGetPage', { params });

    tableData.value = data.list.map((item, index) => ({
        ...item,
        actionsVisible: false // 初始化操作按钮不可见
    }));
    total.value = data.total;
}

// 删除
const doDelete = async (id) => {
    const {data} = await axios.delete(`/api/dishes/${id}`);
    if (data > 0) {
        doFlushPage();		// 删除成功，刷新表格数据
        ElMessage.success('删除成功');
    } else {
        ElMessage.error('删除失败');
    }
}

// 刷新页面
const doFlushPage = () => {
    resetForm(formRef.value);
    doList();
}

// 初始化
onMounted(() => {
    doList();   // 查询数据
})

// 显示操作按钮
const showActions = (index) => {
    actionsVisible.value[index] = true;
}

// 隐藏操作按钮
const hideActions = (index) => {
    actionsVisible.value[index] = false;
}

//--------------------------- 新增 对话框 ---------------------------
const addDialogVisible = ref(false);
const showAddDialog = () => {
    addDialogVisible.value = true;
}

//--------------------------- 更新 对话框 ---------------------------
const updateDialogVisible = ref(false);
const updatePageRef = ref(); // 组件引用
const showUpdateDialog = (obj) => {
    updateDialogVisible.value = true;
    nextTick(() => {
        updatePageRef.value.handleUpdateData(obj);
    })
}

//--------------------------- 详显 页面---------------------------
// 详显组件引用 -> 绑定到
const detailPageRef = ref();
const showDetailPage = (obj) => {
    detailPageRef.value.handleDetailData(obj);
}
</script>

<style scoped>
.dish-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
    padding: 20px;
}

.dish-card {
    position: relative;
    border: 1px solid #ddd;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.3s ease;
}

.dish-card:hover {
    transform: scale(1.05);
}

.dish-image {
    width: 100%;
    height: 250px;
    object-fit: cover;
}

.dish-name {
    font-size: 16px;
    font-weight: bold;
    text-align: center;
    margin: 10px 0;
}

.dish-price {
    font-size: 14px;
    color: #e67e22;
    text-align: center;
}

.dish-actions {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 10px;
    display: flex;
    justify-content: space-around;
    opacity: 0; /* 默认隐藏 */
    transition: opacity 0.3s ease;
}

.dish-card:hover .dish-actions {
    opacity: 1; /* 悬停时显示 */
}
</style>